package com.zx.platform.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.platform.dao.model.Menus;
import com.zx.platform.dao.model.Roles;
import com.zx.platform.service.MenusService;
import com.zx.platform.service.RolesService;
import com.zx.platform.service.domain.RolesDomain;
import com.zx.platform.service.model.RoleMenusModel;
import com.zx.platform.service.model.RolesModel;
import com.zx.platform.utils.PmpUtils;
import com.zx.utils.WebUtils;

@Controller
@RequestMapping("/manage/roles")
public class RolesController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(RolesController.class);

	@Autowired
	private RolesService rolesService;

	@Autowired
	private MenusService menusService;

	@Autowired
	private AgentInfoService agentInfoService;

	/**
	 * 进入列表页面
	 */
	@RequestMapping("/list")
	public String list(RolesDomain domain, Model model,
	                   HttpServletRequest request) {

		try {// 初始化信息
			Integer pageNum = domain.getPageNum();
			Integer pageSize = domain.getPageSize();
			Integer pageCount = domain.getPageCount();
			if (null == pageNum) {
				pageNum = 1;
			}
			if (null == pageSize) {
				pageSize = 10;
			}

			Map map = rolesService.getPageByDomain(pageSize, pageNum, domain);
			List<RolesModel> rolesModelList = (List<RolesModel>) map.get("list");
			int recordCount = Integer.valueOf(map.get("count").toString());
			// 页面信息
			if (pageSize * pageNum > recordCount + pageSize - 1) {
				pageNum = 1;
			}
			model.addAttribute("list", rolesModelList);
			model.addAttribute("pageNum", pageNum);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageCount",
					PmpUtils.getPageCount(recordCount, pageSize));
			model.addAttribute("recordCount", recordCount);
			model.addAttribute("model", domain);
			return "/jsp/platform/roles/rolesList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 表单提交日期绑定
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	/**
	 * 弹出的新增修改页面
	 *
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(RolesModel rolesModel, Model model,
	                   HttpServletRequest request) {
		try {

			Integer roleId = rolesModel.getRoleId();
			if (roleId != null && roleId != -1) {
				rolesModel = rolesService.getModelByKey(roleId);
			}
			model.addAttribute("model", rolesModel);
			return "/jsp/platform/roles/rolesEdit";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * @return
	 */
	@RequestMapping("/update")
	public
	@ResponseBody
	RolesModel update(RolesModel model) {
		try {
			rolesService.update(model);
			model.setSuccess(true);
			model.setMsg("保存信息成功");
			log.debug("保存信息成功");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("保存信息失败");
			log.error("保存信息失败" + e.getMessage(), e);
		}
		return model;
	}

	/**
	 * @return
	 */
	@RequestMapping("/delete")
	public
	@ResponseBody
	RolesModel delete(RolesModel model) {
		try {
			rolesService.delete(model);
			model.setSuccess(true);
			model.setMsg("删除信息成功");
			log.debug("删除信息成功");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("删除信息失败");
			log.error("删除信息失败" + e.getMessage(), e);
		}
		return model;
	}

	/**
	 * @return
	 */
	@RequestMapping("/add")
	public
	@ResponseBody
	RolesModel add(RolesModel model) {
		try {
			model.setCreateDate(new Date());
			rolesService.add(model);
			model.setSuccess(true);
			model.setMsg("新增信息成功");
			log.debug("新增信息成功");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("新增信息失败");
			log.error("新增信息失败" + e.getMessage(), e);
		}
		return model;
	}

	/**
	 * 进入角色菜单设置页面
	 */
	@RequestMapping("/editRoleMenus")
	public String editRoleMenus(RolesDomain domain, Model model,
	                            HttpServletRequest request) {

		try {
			List<RolesModel> allRoles = new ArrayList();
			List<Menus> allMenus = new ArrayList();
			List<Menus> menusList = new ArrayList();

			allMenus = menusService.getAllList();
			allRoles = rolesService.getAllList();
			if (domain == null || domain.getRoleId() == null) {
				RolesModel roles = allRoles.get(0);
				domain.setRoleId(roles.getRoleId());
			}
			if (domain != null && domain.getRoleId() != null) {
				// 根据角色查找关联的菜单
				menusList = menusService.getMenusByRoleId(domain.getRoleId());
			}
			model.addAttribute("menusList", menusList);
			model.addAttribute("allMenus", allMenus);
			model.addAttribute("allRoles", allRoles);
			model.addAttribute("model", domain);
			return "/jsp/platform/roles/editRoleMenus";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 角色菜单关联
	 *
	 * @return
	 */
	@RequestMapping("/setRoleMenus")
	public
	@ResponseBody
	RolesModel setRoleMenus(RoleMenusModel model) {
		RolesModel rolesModel = new RolesModel();
		try {
			rolesService.setRoleMenus(model);
			rolesModel.setSuccess(true);
			rolesModel.setMsg("角色菜单设置成功");
			log.debug("角色菜单设置成功");
		} catch (Exception e) {
			rolesModel.setSuccess(false);
			rolesModel.setMsg("角色菜单设置失败");
			log.error("角色菜单设置失败" + e.getMessage(), e);
		}
		rolesModel.setRoleId(model.getRoleId());
		return rolesModel;
	}

	/**
	 * 根据当前登录的用户级别，返回下面的
	 */
	@RequestMapping("/queryDownAgentLevelRole")
	@ResponseBody
	public HashMap<String, Object> queryDownAgentLevelRole(Model model,
	                                                       HttpServletRequest request) {
		try {
			// 查找当前用户对应的代理商
			AgentInfoModel curAgentInfoModel = WebUtils
					.queryCurrentLoginAgentInfo(request);

			return CommonResponseUtils.successResponse(rolesService.getDownAgentRoles(curAgentInfoModel));
		} catch (Exception e) {
			log.error("内部异常", e);
			return CommonResponseUtils.failureResponse();
		}
	}

	@RequestMapping("/queryOperatorRoleForLeftRate")
	public String queryOperatorRoleForLeftRate(Model model,
	                                           HttpServletRequest request) {
		try {
			// 查找当前用户对应的代理商
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);

			List<Roles> rolesList = rolesService.getDownAgentRoles(curAgentInfoModel);
			model.addAttribute("list", rolesList);
			return "/jsp/map/agentLeft/agentLeftList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}
}
